package dao

import (
	"fitness/internal/entity/system"
	"fitness/pkg/utils"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"strconv"
)

type LogDao struct {
	DB  *gorm.DB
	Log *zap.Logger
}

func NewLogDao(db *gorm.DB, logger *zap.Logger) *LogDao {
	return &LogDao{
		DB:  db,
		Log: logger,
	}
}

func (logDao *LogDao) ListPagedLogs(queryParams system.LogPageQuery) (utils.Page[system.LogPageVO], error) {
	sql := `SELECT
            t1.id,
            t1.module,
            t1.content,
            t1.request_uri,
            t1.method,
            t1.ip,
            CONCAT(t1.province," ", t1.city) AS region,
            t1.execution_time,
            CONCAT(t1.browser," ", t1.browser_version) AS browser,
            t1.os,
            t1.create_time,
            t2.nickname AS operator
        FROM
            sys_log t1
            LEFT JOIN sys_user t2 ON t1.create_by = t2.id
            where t1.is_deleted = 0 `

	where := ""
	if queryParams.PageQuery.Keywords != nil && *queryParams.PageQuery.Keywords != "" {
		where = ` and (
		          t1.content LIKE '%` + *queryParams.PageQuery.Keywords + `%'
		           OR t1.ip LIKE '%` + *queryParams.PageQuery.Keywords + `%'
		           OR t2.nickname LIKE '%` + *queryParams.PageQuery.Keywords + `%'
		           )`
	}
	if queryParams.StartDate != nil {
		where = where + " AND t1.create_time >= '" + *queryParams.StartDate + `'`
	}
	if queryParams.EndDate != nil {
		where = where + " AND t1.create_time <= '" + *queryParams.EndDate + `'`
	}
	if queryParams.UserType != nil {
		where = where + " AND t1.user_type = " + strconv.FormatUint(uint64(*queryParams.UserType), 10)
	}

	sql = sql + where + " ORDER BY  t1.create_time DESC"

	var totalRecords int64
	page := *queryParams.PageQuery.PageNum      // 当前页码
	pageSize := *queryParams.PageQuery.PageSize // 每页数据量

	// 计算偏移量
	offset := (page - 1) * pageSize
	var pageVOS = make([]system.LogPageVO, 0)
	var pages = make([]system.LogPage, 0)
	var res utils.Page[system.LogPageVO]
	//获取数据
	err := logDao.DB.Raw(sql+" LIMIT ? , ?", offset, pageSize).Scan(&pages).Error
	if err != nil {
		return res, err
	}
	// 获取总记录数
	err = logDao.DB.Model(&system.SysLog{}).
		Raw("select count(1) from sys_log t1 LEFT JOIN sys_user t2 ON t1.create_by = t2.id  where t1.is_deleted = 0 " + where).
		Scan(&totalRecords).Error
	if err != nil {
		return res, err
	}
	for _, log := range pages {
		vo := system.LogPageVO{
			ID:            log.ID,
			Module:        LogModuleEnum[log.Module],
			Content:       log.Content,
			RequestUri:    log.RequestUri,
			Method:        log.Method,
			Ip:            log.Ip,
			Region:        "",
			Browser:       log.Browser,
			Os:            log.Os,
			ExecutionTime: log.ExecutionTime,
			CreateBy:      log.CreateBy,
			CreateTime:    log.CreateTime.Format("2006-01-02 15:04:05"),
			Operator:      log.Operator,
		}
		pageVOS = append(pageVOS, vo)
	}
	res.List = pageVOS
	res.Total = totalRecords
	return res, nil
}

var LogModuleEnum = map[string]string{
	"LOGIN": "登录",
	"USER":  "用户",
	"ROLE":  "角色",
	"DEPT":  "部门",
	"MENU":  "菜单",
	"DICT":  "字典",
	"OTHER": "其他",
}
